import 'nprogress/nprogress.css'; // progress bar style

import NProgress from 'nprogress'; // progress bar
import { storeToRefs } from 'pinia';
import { MessagePlugin } from 'tdesign-vue-next';

import router from '@/router';
import { getPermissionStore, useUserStore } from '@/store';

NProgress.configure({ showSpinner: false });

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  const permissionStore = getPermissionStore();
  const userStore = useUserStore();
  const { routers } = storeToRefs(permissionStore);
  if (to.path === '/login') {
    next();
    NProgress.done();
    return;
  }
  console.info(permissionStore);
  console.info(routers.value);
  console.info(to.path);
  const parts = to.path.split('/');
  const directPath = `/${parts[1]}`;

  const paths = routers.value.map((route) => route.path);
  // 打印结果
  const isAllowed = paths.includes(directPath);
  console.info(userStore.token);
  const isLogin = userStore.token.length > 0;
  if (!isAllowed) {
    MessagePlugin.error('无权限访问');
    next('/login');
    NProgress.done();
    return;
  }
  // 检查目标路由是否在允许的路由列表中
  next();

  NProgress.done();
});

router.afterEach((to) => {
  if (to.path === '/login') {
    const userStore = useUserStore();
    userStore.logout();
  }
  NProgress.done();
});
